package com.yuesystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuesystem.common.R;
import com.yuesystem.dto.requestbody.AreaRequestBody;
import com.yuesystem.dto.responsebody.AcademyNumberResponseBody;
import com.yuesystem.dto.responsebody.AcademySearchResponseBody;
import com.yuesystem.entity.Academy;
import com.yuesystem.entity.AcademyItem;
import com.yuesystem.entity.ChangeItem1;
import com.yuesystem.entity.FixedItem;
import com.yuesystem.entity.Office;
import com.yuesystem.entity.OfficeItem;
import com.yuesystem.service.AcademyItemService;
import com.yuesystem.service.AcademyService;
import com.yuesystem.service.ChangeItem1Service;
import com.yuesystem.service.FixedItemService;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

import com.yuesystem.service.impl.FeedbackServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 书院控制类.
 */
@RestController
@RequestMapping("/academies")
@CrossOrigin
@Slf4j
public class AcademyController {
  @Autowired
  private AcademyService academyService;

  @Autowired
  private FixedItemService fixedItemService;
  
  @Autowired
  private ChangeItem1Service changeItem1Service;
  
  @Autowired
  private AcademyItemService academyItemService;
  
  /**
   * 增加官职.
   */
  @RequestMapping("/add")
  public R<String> addOffice(@RequestBody Academy academy) {
    if (academy.getAcademyName() == null) {
      return R.error("书院名不为空");
    }
    if (academy.getCorpus() == null) {
      return R.error("书院介绍不为空");
    }
    if (academyService.add(academy)) {
      ChangeItem1 changeItem1 = new ChangeItem1();
      changeItem1.setUserId(FeedbackServiceImpl.userId);
      changeItem1.setOperate("增加");
      changeItem1.setSubjectNew(academy.getAcademyName());
      changeItem1.setRelationNew("介绍");
      changeItem1.setObjectNew(academy.getCorpus());
      changeItem1Service.save(changeItem1);
      return R.success("添加成功");
    }
    return R.error("书院已存在，添加失败");
  }
  
  /**
   * 删除官职.
   */
  @RequestMapping("/delete")
  public R<String> deleteOffice(@RequestParam Long id) {
    Academy academy = academyService.getById(id);
    if (academy == null) {
      return R.error("删除失败");
    }
    List<AcademyItem> list = academyItemService.getItems(id);
    for (AcademyItem academyItem : list) {
      academyItem.setIsDeleted(1);
      academyItemService.updateById(academyItem);
    }
    ChangeItem1 changeItem1=new ChangeItem1();
    changeItem1.setUserId(FeedbackServiceImpl.userId);
    changeItem1.setOperate("删除");
    changeItem1.setSubjectOld(academy.getAcademyName());
    changeItem1.setRelationOld("介绍");
    changeItem1.setObjectOld(academy.getCorpus());
    changeItem1Service.save(changeItem1);
    academyService.removeById(academy);
    return R.success("删除成功");
  }
  
  /**
   * 更改corpus内容
   */
  @PostMapping("/update")
  public R<String> update(@RequestBody Academy academy1) {
    Long id = academy1.getId();
    String corpus = academy1.getCorpus();
    Academy academy = academyService.getById(id);
    if (academy == null) {
      return R.error("更改失败");
    }
    if (corpus == null) {
      return R.error("介绍不为空");
    }
    String oldCourpus=academy.getCorpus();
    academy.setCorpus(corpus);
    academyService.updateById(academy);
    ChangeItem1 changeItem1=new ChangeItem1();
    changeItem1.setUserId(FeedbackServiceImpl.userId);
    changeItem1.setOperate("修改");
    changeItem1.setSubjectOld(academy.getAcademyName());
    changeItem1.setRelationOld("介绍");
    changeItem1.setObjectOld(oldCourpus);
    changeItem1.setSubjectNew(academy.getAcademyName());
    changeItem1.setRelationNew("介绍");
    changeItem1.setObjectNew(academy.getCorpus());
    changeItem1Service.save(changeItem1);
    return R.success("编辑成功");
  }

  /**
   * 获得某个省份的书院分布情况.
   *
   * @param province 某个省份
   * @param page     起始页
   * @param pageSize 页数
   * @return 书院搜索应答类
   */
  @GetMapping("/distribute/{province}/{page}/{pageSize}")
  public R<Page<AcademySearchResponseBody>> getDistribute(
      @PathVariable(name = "province") String province,
      @PathVariable int page, @PathVariable int pageSize) {
    Page<Academy> pageInfo = academyService.getPage(page, pageSize, province);
    Page<AcademySearchResponseBody> page1 = new Page<>(page, pageSize);

    BeanUtils.copyProperties(pageInfo, page1, "records");
    List<Academy> records = pageInfo.getRecords();

    List<AcademySearchResponseBody> list = records.stream().map((item) -> {
      AcademySearchResponseBody body = new AcademySearchResponseBody();
      body.setId(item.getId());
      body.setAcademyName(item.getAcademyName());
      if (item.getCorpus().length() > 60) {
        body.setSimpleCorpus(item.getCorpus().substring(0, 60) + "......");
      } else {
        body.setSimpleCorpus(item.getCorpus());
      }
      return body;
    }).collect(Collectors.toList());

    page1.setRecords(list);

    return R.success(page1);
  }

  /**
   * 根据书院名称来搜索对应的书院，返回一个书院类集合.
   *
   * @param name     书院名称
   * @param page     起始页
   * @param pageSize 页数
   * @return 书院搜索应答类
   */
  @GetMapping("/search")
  public R<Page<AcademySearchResponseBody>> search(
      @RequestParam String name, @RequestParam int page,
      @RequestParam int pageSize) {
    Page<Academy> pageInfo = new Page<>(page, pageSize);
    Page<AcademySearchResponseBody> page1 = new Page<>(page, pageSize);
    LambdaQueryWrapper<Academy> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.like(name != null || !name.isEmpty(), Academy::getAcademyName, name);
    academyService.page(pageInfo, queryWrapper);

    // 对象拷贝，把pageInfo的内容拷贝进dtoPage，忽略records，就是第三个参数中写的那样
    BeanUtils.copyProperties(pageInfo, page1, "records");
    List<Academy> records = pageInfo.getRecords();

    List<AcademySearchResponseBody> list = records.stream().map((item) -> {
      AcademySearchResponseBody body = new AcademySearchResponseBody();
      body.setId(item.getId());
      body.setAcademyName(item.getAcademyName());
      if (item.getCorpus().length() > 60) {
        body.setSimpleCorpus(item.getCorpus().substring(0, 60) + "......");
      } else {
        body.setSimpleCorpus(item.getCorpus());
      }
      return body;
    }).collect(Collectors.toList());

    page1.setRecords(list);

    return R.success(page1);
  }

  /**
   * 随机获得八个书院推荐.
   *
   * @return 书院类
   */
  @GetMapping("/introduce")
  public R<List<Academy>> introduce() {
    Random random = new Random();
    List<Integer> numberList = new ArrayList<>();

    while (numberList.size() < 8) {
      Integer number = random.nextInt(1559);
      if (!numberList.contains(number)) {
        numberList.add(number);
      }
    }

    List<Academy> academyList = new ArrayList<>();
    for (Integer i : numberList) {
      Academy academy = academyService.getById(i);
      academyList.add(academy);
    }

    return R.success(academyList);
  }

  /**
   * 根据书院id获得书院信息.
   *
   * @param id 书院id
   * @return 书院类
   */
  @GetMapping("/{id}")
  public R<Academy> getById(@PathVariable Long id) {
    Academy academy = academyService.getById(id);
    return R.success(academy);
  }

  /**
   * 获得中国七大地区分布.
   *
   * @return 地区分布响应类
   */
  @GetMapping("/area")
  public R<List<AreaRequestBody>> getByArea() {
    List<AreaRequestBody> list = academyService.getByArea();
    return R.success(list);
  }

  /**
   * 获得各省份书院数目.
   */
  @GetMapping("/number")
  public R<List<AcademyNumberResponseBody>> getNumber() {
    List<AcademyNumberResponseBody> list = academyService.getNumber();
    return R.success(list);
  }


  /**
   * 测试用.
   */
  @GetMapping("/test")
  public R<List<Map<String, Object>>> test() {
    QueryWrapper<FixedItem> queryWrapper = new QueryWrapper<>();
    queryWrapper.select("relation , count(*) as number")
        .groupBy("relation");
    List<Map<String, Object>> maps = fixedItemService.listMaps(queryWrapper);
    return R.success(maps);
  }

}
